import React, { Component } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import {
    Breadcrumb,
} from 'antd';

import { addTab } from '@/utils/utils';

interface PageHeaderProps {
    dispatch?: Dispatch;
    menuInfo?: any[];
    tabs?: any[];
}

interface PageHeaderState {

}

@connect(({
    menu: { menuInfo = [] },
    global: { tabs = [] },
}: any) => ({
    menuInfo,
    tabs,
}))

class PageHeaderInfoElem extends Component<PageHeaderProps, PageHeaderState> {
    state = {}

    handleRouter = ({ name, url }: any) => {
        const { dispatch } = this.props;
        addTab(dispatch, {
            name,
            url,
            isTopMenu: true,
        });
    }

    render() {
        const { menuInfo, tabs }: any = this.props;
        const { pathname, search } = window.location;

        const currentMenu: any = menuInfo.map((item: any) => ({
            name: item.name,
            target_tab: item.target_tab,
            firstTab: item.children && item.children.length && item.children[0],
            currentTab: item.children
                && item.children.find((subMenu: any) => pathname.indexOf(subMenu.uri) >= 0),
        })).find((item: any) => pathname.indexOf(item.target_tab) >= 0);

        const { currentTab = {} } = currentMenu;

        // 获取二级页面的名称和uri 修改
        let subMenu;
        if (!search) {
            subMenu = tabs.find((item: any) => item.url.indexOf(pathname) >= 0);
        } else {
            subMenu = tabs.find((item: any) => item.url.indexOf(decodeURIComponent(search)) >= 0);
        }

        return (
            <div className="pageTitle">
                <Breadcrumb>
                    <Breadcrumb.Item href="/">首页</Breadcrumb.Item>
                    <Breadcrumb.Item
                        onClick={() => this.handleRouter({
                            name: currentMenu.firstTab.name,
                            url: currentMenu.firstTab.uri,
                        })}
                    >{currentMenu.name}
                    </Breadcrumb.Item>
                    <Breadcrumb.Item
                        onClick={() => this.handleRouter({
                            name: currentTab.name,
                            url: currentTab.uri,
                        })}
                    >{currentTab.name}
                    </Breadcrumb.Item>
                    {subMenu && pathname !== currentTab.uri && (
                        <Breadcrumb.Item>{subMenu.name}</Breadcrumb.Item>
                    )}
                </Breadcrumb>
            </div>
        );
    }
}

export default PageHeaderInfoElem;
